import os, shutil, time


def check_local_path(file_name):
    """
        检查现存路径，有则返回，无则创建
    :return: 路径
    """
    try:
        with open('%s.txt' % file_name, 'r+') as f:
            existing_path = f.read()
            if existing_path:
                print('The existing {} directory is:{}'.format(file_name, existing_path))
                # 判断已有的目录是否是期望的
                change = input('Change to other directory?\n(Type anything as YES, or press Enter directly as NO):')
                if change:  # 若change有值说明需要更改
                    print('Removed old directory')
                    raise FileNotFoundError     # 抛出异常，就会去执行except中的代码
                else:
                    return existing_path
            else:
                new_path = input('No %s directory detected, please enter path:' % file_name)
                f.write(new_path)
                return new_path
    except FileNotFoundError:
        with open('%s.txt' % file_name, 'w') as f:
            new_path = input('No %s directory detected, please enter path:' % file_name)
            f.write(new_path)
            return new_path


def mk_local_path(date, project, parent_path):
    """
        创建本地路径
    :return: local_path 本地的路径
    """
    local_folder = '{} - {}'.format(date, project)   # 给本地文件夹命名
    local_path = os.path.join(parent_path, local_folder)     # 拼接, 得到本地的路径
    if not os.path.exists(local_path):
        os.chdir(parent_path)    # 切换到本地任务目录
        os.mkdir(local_folder)      # 创建今天的任务文件夹
        print('Local folder created:%s' % local_path)
    else:
        print('The existing folder will be used:%s' % local_path)
    return local_path


def go_to_folder(date, project, share_path):
    """
        切换到TestReport当天的文件夹下
    :return:
    """
        # 如果有产品的子目录，则进入
    list_path = os.path.join(share_path, date, project)
    if os.path.exists(list_path):
        os.chdir(list_path)
        # 否则，说明表在当天的文件夹中
    elif os.path.exists(os.path.join(share_path, date)):
        list_path = os.path.join(share_path, date)
        os.chdir(list_path)
    else:   # 如果以上都不成立，则说明还没创建今天的夹子
        print('There is no [{}] folder here\nPlease recheck the folder: {}'.format(date, share_path))
        time.sleep(2)   # 反应时间，让用户看到上面的信息
        os.startfile(share_path)  # 打开共享文件夹
        exit()
    print('current path is:' + os.getcwd())
    return list_path


def choose_file(path):
    """
        选择需要的文件
    :param path:文件路径
    :return:被选中的文件名
    """
    list_dir = os.listdir(path)
    for i in range(len(list_dir)):  # 遍历目标文件夹下的所有文件
        print('[{}]----{}\n'.format(i, list_dir[i]))
    # 输入序号选择需要的文件
    file_code = input('Select file(s) (separator","):').split(',')
    file_list = [list_dir[int(i)] for i in file_code]
    return file_list


def copy_file(file_list, source, target, date):
    """
        批量复制文件到指定目录，并重命名
    :param file_list: 需要复制的文件列表
    :param source: 文件源目录
    :param target: 目的地目录
    """
    os.chdir(source)
    for file in file_list:
        shutil.copy(file, target)   # 复制文件到指定目录
    print('Copy successed, there are {} file(s) in the folder:'.format(len(file_list)))
    os.chdir(target)
    for file in os.listdir(target):
        os.rename(file, '{}-{}'.format(date, file))    # 重命名表文件
    time.sleep(2)


if __name__ == '__main__':
    share_path = check_local_path('share')
    parent_path = check_local_path('local')
    # 获取 产品名 和 日期
    date = input('Please enter date for today(e.g. 0506):')
    project = input('Please enter your tasks for today:')
    # 先去到需要复制文件的目录下
    file_path = go_to_folder(date, project, share_path)
    # 挑选需要复制的文件
    file_list = choose_file(file_path)
    # 创建本地文件夹
    local_path = mk_local_path(date, project, parent_path)
    # 复制文件
    copy_file(file_list, file_path, local_path, date)
    os.startfile(local_path)  # 打开本地文件夹
